package com.ruoyi.web.controller.system;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class CosFileUploadController {

    // Tencent COS configuration (injected from application.properties)
    @Value("${tencent.cos.secretId}")
    private String secretId;

    @Value("${tencent.cos.secretKey}")
    private String secretKey;

    @Value("${tencent.cos.region}")
    private String region;

    @Value("${tencent.cos.bucket}")
    private String bucket;

    @Value("${file.upload-path}")
    private String localUploadPath;

    @PostMapping("/pdf")
    public ResponseEntity<Map<String, Object>> uploadPdf(
            @RequestParam("file") MultipartFile file,
            @RequestParam("id") String id,
            @RequestParam("save_file_name") String saveFileName) {
        Map<String, Object> response = new HashMap<>();

        try {
            // Validate file
            if (file.isEmpty()) {
                response.put("error", "File is empty");
                return ResponseEntity.badRequest().body(response);
            }
            if (!file.getContentType().equals("application/pdf")) {
                response.put("error", "Only PDF files are allowed");
                return ResponseEntity.badRequest().body(response);
            }

            // Save file locally
            File localFile = new File(localUploadPath + File.separator + saveFileName);
            file.transferTo(localFile);

            // Initialize Tencent COS client
            COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            COSClient cosClient = new COSClient(credentials, clientConfig);

            // Prepare COS upload
            String key = id + ".pdf"; // File name in COS (e.g., <id>.pdf)
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("application/pdf"); // Set content type
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, localFile);
            putObjectRequest.setMetadata(metadata); // Attach metadata to the request

            // Upload to COS
            cosClient.putObject(putObjectRequest);

            // Generate file URL
            String fileUrl = String.format("https://%s.cos.%s.myqcloud.com/%s", bucket, region, key);
            response.put("url", fileUrl);
            response.put("message", "File uploaded successfully");

            // Clean up local file
            localFile.delete();

            // Close COS client
            cosClient.shutdown();

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            response.put("error", "Failed to save file locally: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        } catch (CosClientException e) {
            response.put("error", "Failed to upload to COS: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}